﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using DevExpress.LookAndFeel;
using td.Core;
using System.Configuration;
using td.Core.Xml;
using System.Reflection;
using td.Core.Security;
using System.Security;
using CG.Security.Principal;
using System.Threading;

namespace MainForm
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            DevExpress.Skins.SkinManager.EnableFormSkins();
            DevExpress.UserSkins.OfficeSkins.Register();
            DevExpress.UserSkins.BonusSkins.Register();

            //从配置文件中获取默认皮肤的名字
            var skin = System.Configuration.ConfigurationManager.AppSettings["Skin"];
            //载入默认的皮肤
            UserLookAndFeel.Default.SetSkinStyle(skin);
            //设置皮肤变化事件
            UserLookAndFeel.Default.StyleChanged += new EventHandler(Default_StyleChanged);

            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);

            try
            {
                if (!Login()) return;
      
                WorkBenchSingleTon.WorkBench.WorkBenchCreated += new EventHandler(WorkBench_WorkBenchCreated);

                AddIn addin = AddIn.GetInstance();
                //读取插件配置信息
                try
                {
                    addin.LoadFromFile(AddIn.DefaultConfigXml);
                
                    td.Core.SplashScreenForm.ShowSplashScreen(addin.Name+"  "+addin.Version);
                    
                    WorkBenchSingleTon.WorkBench.InitializeWorkbench();
                   
                }
                catch (Exception ee)
                {
                    MessageBox.Show("没有找到插件配置文件！");
                }
                
                Application.Run(WorkBenchSingleTon.WorkBench);
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.ToString());
            }
        }

        static void WorkBench_WorkBenchCreated(object sender, EventArgs e)
        {
            CloseSplashScreen();
        }
        static void CloseSplashScreen()
        {
            if (SplashScreenForm.SplashScreen != null)
            {
                SplashScreenForm.SplashScreen.BeginInvoke(new MethodInvoker(SplashScreenForm.SplashScreen.Dispose));
                SplashScreenForm.SplashScreen = null;
            }
        }
        public static bool Login()
        {
            try
            {
                // Prompt the user for credentials.
                LoginForm form = new LoginForm();
                form.TopMost = true;

                // Did the user fail to provide credentials?
                if (form.ShowDialog() != DialogResult.OK)
                {

                    //this.Close();
                    return false;

                } // End if the user failed to login.

                // Did we fail to authenticate the credentials?
                if (!CG.Security.SecurityManager.Authenticate(form.UserName, form.Password))
                {

                    MessageBox.Show("Failed to authenticate the user!");
                    //this.Close();

                    return false;

                } // End if the credentials were not authenticated.
               
                // Set the default principal for the rest of the application.
                System.AppDomain.CurrentDomain.SetThreadPrincipal(
                    new CustomPrincipal(new CustomIdentity(form.UserName))
                    );
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.ToString());
                return false;
            }
            return true;
        }

 
        static void Default_StyleChanged(object sender, EventArgs e)
        {
            string skin = (sender.ToString().Split(':'))[1].TrimStart();

            SetValue("Skin", skin);

        }
        /// <summary>  
        /// 写入值  
        /// </summary>  
        /// <param name="key"></param>  
        /// <param name="value"></param>  
        public static void SetValue(string key, string value)
        {
            //增加的内容写在appSettings段下 <add key="RegCode" value="0"/>  
            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            if (config.AppSettings.Settings[key] == null)
            {
                config.AppSettings.Settings.Add(key, value);
            }
            else
            {
                config.AppSettings.Settings[key].Value = value;
            }
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");//重新加载新的配置文件   
        }

        /// <summary>  
        /// 读取指定key的值  
        /// </summary>  
        /// <param name="key"></param>  
        /// <returns></returns>  
        public static string GetValue(string key)
        {
            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            if (config.AppSettings.Settings[key] == null)
                return "";
            else
                return config.AppSettings.Settings[key].Value;
        }


        static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            MessageBox.Show(e.Exception.ToString());
        }
    }
}